import { useCallback, useEffect, useState } from "react";
import { $message, SUCCESS_CODE } from 'utils/CommonUtil';
/**
 * 
 * @param {*} fetchDataFn 请求数据接口
 * @param {*} initialSearchParams 初始搜索参数
 * @param {*} initialPagination 初始分页参数
 * @param {*} callBack 接口调用完成后的回调函数
 * @returns 
 */
export default function useFetchWithPageTable(fetchDataFn, initialSearchParams = {}, initialPagination = {current: 1, pageSize: 10}, callBack) {

  // 数据
  const [data, setData] = useState([]);

  // 查询参数
  const [searchParams, setSearchParams] = useState(initialSearchParams);

  // 分页状态
  const [pagination, setPagination] = useState(initialPagination);
  // 记录总条数
  const [total, setTotal] = useState(0);
  const loadData = useCallback(async () => {

    try {
      const params = {
        ...searchParams,
        pageNum: pagination.current,
        pageSize: pagination.pageSize
      }
      // console.log("params = ", params);
      const res = await fetchDataFn(params);
      if (res.code === SUCCESS_CODE) {
        setData(res.data.list);
        setTotal(res.data.total);
      }
      callBack && callBack();   // 接口调用完成后的回调函数
    } catch (error) {
      console.log('获取数据失败!');
    }
  }, [fetchDataFn, searchParams, pagination]);

  // 初始加载数据
  useEffect(() => {
    console.log("初始加载数据....");
    loadData();
  }, [loadData])

  // 处理查询条件变化
  const setSearch = (newParams) => {
    setSearchParams(newParams);
    setPagination(prev => ({ ...prev, current: 1 }));
  };

  // 处理分页变化
  const handlePaginationChange = (newPagination) => {
    setPagination({
      current: newPagination.current,
      pageSize: newPagination.pageSize,
    });
  };

   // 重置所有条件
   const reset = () => {
    setSearchParams(initialSearchParams);
    setPagination(initialPagination);
  };

  // 手动触发查询（例如点击查询按钮时）
  const doSearch = () => {
    console.log("搜索按钮点击");
    
    loadData();
  };


  return {
    data,
    total,
    searchParams,
    pagination,
    
    setSearch,
    handlePaginationChange,
    reset,
    doSearch
  }

}